import isEmpty from 'loadsh/isEmpty'
import { CORPID, SPACEID } from '/constData/requestFun/_globalData';
import { GetInfoPicture, GetPreviewImage, PostDeleteData, PostInfoPicture, GetTapeoutPaymengtInfo, PostTapeoutPaymengtInfo, GetchipPaymentUnitInfo, GetchipPaymentBankInfo, GetchipPaymentAccountInfo, GetchipPaymentNumberInfo } from '/constData/requestFun/_httpRequest';
import { ChipPaymentDeleteData, GetChipPayment, GetchipPaymentBanks, GetChipPaymentById, GetchipPaymentNextId, GetchipPaymentReceivingUnit, PostChipPayment } from '/constData/requestFun/_teseRequest';
import { POLICIES } from '/constData/_';
import compact from 'loadsh/compact'
import { URL_GET_CHIPPAYMENTUNIT } from '/constData/requestFun/_constUrl';
Page({
  data: {
    approve: [],
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    Payment: [
      { value: '公对公转账', label: '公对公转账' },
      { value: '年终付款', label: '年终付款' },
      { value: '其他付款', label: '其他付款' },
    ],
    Rate: [
      { value: '人民币', label: '人民币' },
      { value: '其他类', label: '其他类' },
    ],
    TotalMoney: [
      { value: '小于50万', label: '小于50万' },
      { value: '大于等于50万', label: '大于等于50万' },
    ],
    tapoutinfo: {//流片付款数据
      CorpId: '',
      ContractNumber: '',
      ReasonPayment: '',
      DatePayment: '',
      PaymentMethods: '公对公转账',
      ReceivingUnit: '',
      Bank: '',
      Account: '',
      RateSelection: '',
      Amount: '',
      largeAmount: '',
      Unit: '',
      TotalAmount: '',
      PaymentType: '',
      ProofPayment: '[]',
      Advances: '',
      ContractOrder:'[]',
      Remark: '',
    },
    displayProofPayment: [],
    displayContractOrder: [],
    ReceiveData: [],
    UnitData: [
    ],//收款单位数据
    BankData: [
    ],//开户行数据
    AccountData: [
    ],//银行账号数据
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    ChipPaymentDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  onUnitChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        Unit: e,
      }
    })
  },
  onAmountChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        Amount: e,
        largeAmount: intToChinese(e)
      }
      , approve: POLICIES.TAPEOUTMONEY_POLICIES(e)
    })


  },
  onRemarkChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        Remark: e
      }
    })
  },
  onAdvancesChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        Advances: e
      }
    })
  },
  onPaymentTypeChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        PaymentType: e
      }
    })
  },
  onTotalAmountChange(value) {
    console.log('value,', value);
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        TotalAmount: value
      }
      , approve: POLICIES.TAPEOUTSUMMONEY_POLICIES(value)
    })

  },
  onRateSelectionChange(value) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        RateSelection: value
      }
    });
  },
  onAccountChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        Account: e
      }
    })
  },
  handleDataListChange(val) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        ReceivingUnit: val
      }
    })
  },
  onBankChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        Bank: e
      }
    })
  },
  onReceivingUnitChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        ReceivingUnit: e
      }
    })
  },
  onPaymentChange(value) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        PaymentMethods: value
      }
    });
  },
  handleOk(date, format, e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        DatePayment: date
      },
    })
  },
  onReasonPaymentChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        ReasonPayment: e
      }
    })
  },
  onContractNumberChange(e) {
    this.setData({
      tapoutinfo: {
        ...this.data.tapoutinfo,
        ContractNumber: e
      }
    })
  },
  //获取数据
  onLoad() {
    GetchipPaymentNextId((res)=>{
      this.setData({
        tapoutinfo: {
          ...this.data.tapoutinfo,
          ContractNumber: res.data
        }
      })
    })
    GetchipPaymentReceivingUnit((res)=>{
      this.setData({
        UnitData: res.data
      })
    })
    GetchipPaymentBanks((res)=>{
      this.setData({
        BankData: res.data
      })
    })
    GetchipPaymentBanks((res)=>{
      this.setData({
        AccountData: res.data
      })
    })

    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetChipPayment((res) => {
          const cacheData = res.data.map(it => {
            if (it.item1.corpId === storage.data.result.userid) {
              it.item1['displayProofPayment'] = JSON.parse(it.item1.proofPayment)
              it.item1['displayContractOrder'] = JSON.parse(it.item1.contractOrder)
              return it
            }
          })
          this.setData({
            tapoutinfo: {
              ...this.data.tapoutinfo,
              CorpId: storage.data.result.userid
            },
            ReceiveData: compact(cacheData).reverse()
          })
        })
      }
    })
  },
  // 上传数据
  onSubmit(e) {
    PostChipPayment(JSON.stringify(this.data.tapoutinfo),
    (res) => {
      my.alert({
        title: '提交成功',
      });
      GetChipPaymentById(res.data, (res) => {
        this.setData({
          ReceiveData: compact([...this.data.ReceiveData, res.data].map(it => {
            if (it.item1.corpId === this.data.tapoutinfo.CorpId) {
                it.item1['displayProofPayment'] = JSON.parse(it.item1.proofPayment)
                it.item1['displayContractOrder'] = JSON.parse(it.item1.contractOrder)
              return it
            }
          })).reverse()
        })
      })
      this.setData({
        tapoutinfo: {
          ...this.data.tapoutinfo,
          ContractNumber: '',
          ReasonPayment: '',
          DatePayment: '',
          PaymentMethods: '公对公转账',
          ReceivingUnit: '',
          Bank: '',
          Account: '',
          RateSelection: '',
          Amount: '',
          largeAmount: '',
          Unit: '',
          TotalAmount: '',
          PaymentType: '',
          ProofPayment: '[]',
          Advances: '',
          ContractOrder:'[]',
          Remark: '',
        }
      })
    },
    (err) => {
      my.alert({
        title: '提交成功1',
      });
    })
  },
  //上传图片
  onUpload() {
    let imageProofPayment = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      types: ['photo'],
      success: (res) => {
        const srcProofPayment = this.data.tapoutinfo.ProofPayment
        imageProofPayment = res.data
        imageProofPayment.push(...JSON.parse(srcProofPayment))
        this.setData({
          displayProofPayment: imageProofPayment,
          tapoutinfo: {
            ...this.data.tapoutinfo,
            ProofPayment: JSON.stringify(imageProofPayment)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },
  //上传文件
  onUploadFile() {
    let fileContractOrder = ''
    dd.uploadAttachmentToDingTalk({
      types: ['file'],
      file: { spaceId: SPACEID, max: 9, folderId: '' },
      success: (res) => {
        const srcContractOrder = this.data.tapoutinfo.ContractOrder
        fileContractOrder = res.data
        fileContractOrder.push(...JSON.parse(srcContractOrder))
        this.setData({
          displayContractOrder: fileContractOrder,
          tapoutinfo: {
            ...this.data.tapoutinfo,
            ContractOrder: JSON.stringify(fileContractOrder)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },

  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
});

function intToChinese(money) {
  //汉字的数字
  var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  //基本单位
  var cnIntRadice = ['', '拾', '佰', '仟'];
  //对应整数部分扩展单位
  var cnIntUnits = ['', '万', '亿', '兆'];
  //对应小数部分单位
  var cnDecUnits = ['角', '分', '毫', '厘'];
  //整数金额时后面跟的字符
  var cnInteger = '整';
  //整型完以后的单位
  var cnIntLast = '元';
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = '';
  //分离金额后用的数组，预定义
  var parts;
  if (money === '') { //不能用==
    return '';
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf('.') == -1) {
    integerNum = money;
    decimalNum = '';
  } else {
    parts = money.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return chineseStr;
}